package top.humbleyuan.linkedlist;

import top.humbleyuan.datastructure.linkedlist.LinkNode;

/**
 * @Author HumbleYuan
 * @Date 2020/5/19 21:08
 * @Des 链表表示两个数，实现相加
 */
public class LeetCode_2 {
    public static void main(String[] args) {
        // 自己的方法
        m1();
        String s = "";

        // 简洁的写法
        m2();
    }

    public static void m1() {
        LinkNode l1 = new LinkNode(2);
        LinkNode.formLink(l1, new int[]{4, 3});

        LinkNode l2 = new LinkNode(5);
        LinkNode.formLink(l2, new int[]{6, 4});

        LinkNode res = addTwoNumbers(l1, l2);

        LinkNode.headToString(res);
    }



    public static LinkNode addTwoNumbers(LinkNode l1, LinkNode l2) {
        /**
         * 设定一个不变头和一个可变头
         */
        LinkNode res = new LinkNode(-1);
        LinkNode t = res;

        int add = 0;
        while(l1 != null && l2 != null) {

            int sum = l1.val + l2.val + add;
            if(sum >= 10) {
                add = 1;
                sum -= 10;
            } else {
                add = 0;
            }

            // 为当前节点的下一个赋值
            t.next = new LinkNode(sum);
            t = t.next;

            l1 = l1.next;
            l2 = l2.next;
        }

        // 处理剩余链表节点
        singleM(t, l1 == null ? l2 : l1, add);

        return res.next;
    }

    // 处理单个链表
    public static void singleM(LinkNode res, LinkNode single, int add) {
        while(single != null) {
            int sum = single.val + add;
            if(sum >= 10) {
                add = 1;
                sum -= 10;
            } else {
                add = 0;
            }

            res.next = new LinkNode(sum);
            res = res.next;

            single = single.next;
        }

        if(add == 1) {
            res.next = new LinkNode(1);
        }

    }


    // 写法2
    public static void m2() {
        LinkNode l1 = new LinkNode(2);
        LinkNode.formLink(l1, new int[]{4, 3});

        LinkNode l2 = new LinkNode(5);
        LinkNode.formLink(l2, new int[]{6, 4});

        LinkNode head = new LinkNode(0);
        LinkNode temp = new LinkNode(0);
        head.next = temp;

        int add = 0;
        while(l1 != null || l2 != null) {
            int val1 = l1 == null ? 0 : l1.val;
            int val2 = l2 == null ? 0 : l2.val;

            int sum = val1 + val2 + add;
            if(sum > 9) {
                temp.val = sum % 10;
                add = 1;
            } else {
                add = 0;
                temp.val = sum;
            }

            l1 = l1 == null ? null : l1.next;
            l2 = l2 == null ? null : l2.next;

            if(l1 == null && l2 == null) {
                break;
            }

            temp.next = new LinkNode(0);
            temp = temp.next;
        }

        if(add > 0) {
            temp.next = new LinkNode(1);
        }

        LinkNode.headToString(head.next);
    }


}
